<?php

namespace App\Services\RewardGoldPrize;

use App\Models\User;
use App\Models\GoldRecord;
use Illuminate\Support\Facades\DB;

class RewardFirstParentCash
{
    protected GoldRecord $record;

    protected User $user;

    protected ?User $parent = null;

    public function __construct(GoldRecord $record)
    {
        $this->record = $record;
        $this->user = $record->user;
        $this->parent = $this->user->parent;
    }

    protected function canParentReceiveCash(): bool
    {
        $parent = $this->parent;

        if (! $parent) {
            return false;
        } elseif ($this->user->is_mock) {
            return false;
        } elseif ($this->user->fresh()->has_given_parent_cash) {
            return false;
        } else {
            return true;
        }
    }

    protected function settle()
    {
        $cashes = big_decimal(cs('storm')->child_first_record_give_direct_parent_cashes);
        if ($cashes->isLessThanOrEqualTo(0)) return;
        $this->user->update(['has_given_parent_cash' => true]);
        $data = ['gold_record_id' => $this->record->id];
        account_cashes($this->parent)->plusChildFirstRecordCashes($cashes, $data);
    }

    public function reward()
    {
        if (! $this->canParentReceiveCash()) return;

        $this->settle();
    }
}
